<?php
/**
 * 脚本：生产者
 * 向队列中写入消息 from excel or string
 * @Author: Cqiu
 * @Date: 2017-6-6
 */

if (!isset($argv[1])) {
    print_r($argv);
    exit('run like this: php ' . basename(__FILE__) . ' {json_string}|xls file [checkData=1]');
}
$msg = $argv[1];
$checkData = isset($argv[2]) ? true : false;

define('APP_ROOT', __DIR__);

$config = include APP_ROOT . '/config/config.php';

$redis = new Redis();
$redis->connect($config['redis_host'], $config['redis_port']) or die('Redis connect failed!');

$total = 0;

if (is_file($msg)) {
    $apis = include APP_ROOT . '/config/net-car-apis.php';
    $apis2 = [];
    $_sns = [];
    $_apis = [
        'operateArrive',
        'operateDepart',
        'operateLogin',
        'operateLogout',
        'operatePay',

        'orderCreate',
        'orderMatch',

        'positionDriver',
        'positionVehicle'
//        'baseInfoDriverApp',
//        'baseInfoDriverEducate',
//        'baseInfoDriverStat',
//        'baseInfoPassenger',
    ];
    foreach ($apis as $IPCType => $api) {
        $apis2[$api['sn']] = array_merge($api, [
            'IPCType' => $IPCType
        ]);
        if (in_array($IPCType, $_apis)) {
            $_sns[] = $api['sn'];
        }
    }
//    print_r($_sns);exit;

    include APP_ROOT . '/vendor/autoload.php';

    $file = &$msg;

    //=======================
    @ini_set('output_buffering', 'Off');
    @ini_set('zlib.output_compression', 0);
    set_time_limit(5 * 60);
    ini_set('memory_limit', '-1');

//    ob_end_flush();
    ob_implicit_flush(true);

    define('EOL', (PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

    $objPHPExcel = PHPExcel_IOFactory::load($file);
#exit('loaded!');
    $sheets = $objPHPExcel->getAllSheets();
    foreach ($sheets as $objWorksheet) {
        $title = $objWorksheet->getTitle();
        if (preg_match('#^(\d+-\d+)#i', $title, $matches)) {
            if(in_array($matches[1], $_sns))
            if (isset($apis2[$matches[1]])) {
                echo $matches[1] . EOL;
                flush();

                $apiInfo = $apis2[$matches[1]];

                $highestRow = $objWorksheet->getHighestRow();
                $highestColumn = $objWorksheet->getHighestColumn();
                $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);

                //for test
//                $highestRow = min($highestRow, 8);

                //field title
                $fieldTitles = [];
                $row = 3;
                for ($col = 0; $col < $highestColumnIndex; $col++) {
                    $fieldTitles[$col] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                }
                //field value
                $fieldValues = [];
                $records = ['IPCType' => $apiInfo['IPCType']];
                $recordCount = 0;
                if ($checkData) {
                    for ($row = 4; $row <= $highestRow; $row++) {
                        for ($col = 0; $col < $highestColumnIndex; $col++) {
                            $fieldValues[$col] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                        }
                        if (!implode('', $fieldValues)) {
                            continue;
                        }
                        $records[] = $record = array_combine($fieldTitles, $fieldValues);
                        //校验
                        if ($errors = checkPostData($apiInfo, $record)) {
                            print_r($errors);

                            break;
                            //continue;
                        }
                        $recordCount++;
                    }
                } else {
                    for ($row = 4; $row <= $highestRow; $row++) {
                        for ($col = 0; $col < $highestColumnIndex; $col++) {
                            $fieldValues[$col] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                        }
                        if (!implode('', $fieldValues)) {
                            continue;
                        }
                        $records[] = $record = array_combine($fieldTitles, $fieldValues);
                        // 处理文件上传！
                        foreach ($apiInfo['fields'] as $field => $info) {
                            if (isset($info['handle']) && $info['handle'] == 'fileUp') {
                                /*$redis->lPush('net_car_queue', json_encode([
                                    'IPCType' => 'file',
                                    'file'    => $record[$field],
                                    'upPath'  => '/wycftp075/' . strtolower($apiInfo['IPCType'])
                                ])) && print('push ok!' . EOL);*/
                                //ftp save full name
                                $folderName = str_replace([
                                    'baseinfodriver',
                                    'baseinfovehicle',
                                    'baseinfocompany',
                                ], [
                                    'driverinfo',
                                    'vehicleinfo',
                                    'certinfo',
                                ], strtolower($apiInfo['IPCType']));
                                $record[$field] = '/wycftp075/' . $folderName . '/' . basename($record[$field], '.jpg') . '.jpg';
                            }
                        }
                        $record['IPCType'] = $record['CompanyId'] = $apiInfo['IPCType'];
                        $redis->lPush('net_car_queue', json_encode($record)) && print('!');
                        $recordCount++;
                        $total++;
                    }
                }
                echo "\t", $recordCount, EOL;

                //for test
//                file_put_contents('tmp/' . $matches[1], var_export($records, 1));
            }
        }
    }

    $redis->set('total', $total);
    echo "___\ntotal: ", $total, EOL;

    return;

    // {{{ one_sheet_multi_table 读取excel文件数据， 单个sheet， 纵向多个数据字段
    $objWorksheet = $objPHPExcel->getActiveSheet();
    $highestRow = $objWorksheet->getHighestRow();
    $highestColumn = $objWorksheet->getHighestColumn();
    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
    $excelData = array();
    $req_data = [];
    for ($row = 1; $row <= $highestRow; $row++) {
        for ($col = 0; $col < $highestColumnIndex; $col++) {
            $excelData[$row][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
        }

        // section start
        if (preg_match('#^(\d+-\d+) #i', $excelData[$row][0], $matches)) {
            if (isset($apis2[$matches[1]])) {
                //previous section end
                if ($req_data) {
                    echo json_encode($req_data) . EOL;
                    $redis->lPush('net_car_queue', json_encode($req_data)) && print('push ok!' . EOL);
                }
                $req_data = ['IPCType' => $apis2[$matches[1]]['IPCType']];
            } else {
                $req_data = [];
            }
        } // field
        else {
            if (preg_match('#^(\w+)$#i', $excelData[$row][0], $matches)) {
                $req_data[$matches[1]] = $excelData[$row][4];
            }
        }
    }
    //previous section end
    if ($req_data) {
        echo json_encode($req_data);
        $redis->lPush('net_car_queue', json_encode($req_data)) && print('push ok!' . EOL);
    }
    // }}} one_sheet_multi_table

    //================

} else {
    $redis->lPush('net_car_queue', $msg) && print('push ok!');
}


/**
 * 检查 数据
 * @param $apiInfo
 * @param $data
 * @return array
 */
function checkPostData($apiInfo, $data)
{
    $data['CompanyId'] = 'syjcx';
    if (isset($data['State'])) $data['State'] = 1;
    if (isset($data['Flag'])) $data['Flag'] = 1;

    $errors = [];
    foreach ($apiInfo['fields'] as $field => $info) {
        if ($info[0] == '是' && !isset($data[$field])) {
            $errors[] = "{$field}: required!";
            continue;
        }
        if (isset($info['handle']) && function_exists($info['handle'])) {
            $data[$field] = $info['handle']($data[$field]);
        }
        if ($info[1] == '数字型') {
            if ($data[$field] <= 2147483647) $data[$field] += 0;
            else $data[$field] = number_format($data[$field], 0, '', '');//sprintf("%.0f", $data[$field]);
        }
//        if (preg_match('#(Latitude|Longitude)#', $field)) {
//            $data[$field] = intval(600000 * $data[$field]);
//        }
        if (strlen($data[$field]) > ($len = substr($info[2], 1))) {
            $errors[] = "{$field}: too long!{$len}";
        }
        if ('F' == substr($info[2], 0, 1) && strlen($data[$field]) != $len) {
            $errors[] = "{$field}: length => $len !" . ($data[$field]);
        }
    }
    if ($errors) {
        print_r($data);
        return $errors;
    }

    return [];

}

function fileUp($file)
{
    return $file;
}

function unixTime($str)
{
    return $str;
//    return substr_replace($str, '20170904', 0, 8);
}